
import styled from 'styled-components';
import { FC, useEffect, useRef, useState } from "react";
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

export interface SimpleEditorProps {
    language?: 'javascript' | 'markdown' | 'json' | string,
    theme?: 'vs' | string,
    initValue?: string;
    value?: string;
    onCreateCompleted?: (editor: monaco.editor.IStandaloneCodeEditor) => void;
    onChange: (value: string) => Promise<void>;
}

export const SimpleEditor: FC<SimpleEditorProps> = (props) => {

    const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null);

    const monacoEl = useRef(null);

    useEffect(() => {
        if (monacoEl) {
            setEditor((editor) => {
                if (editor) return editor;

                let e = monaco.editor.create(monacoEl.current!, {
                    automaticLayout: true,
                    theme: "vs",
                    value: props.initValue || '',
                    language: props.language || 'markdown'
                });
                props.onCreateCompleted && props.onCreateCompleted(e);

                e.onDidChangeModelContent((event) => {
                    props.onChange && props.onChange(e.getValue())
                });
                return e;
            });
        }

        return () => editor?.dispose();
    }, [monacoEl.current]);

    useEffect(() => {
        if (!props.value) return;
        if (props.value && props.value !== editor?.getValue()) {
            editor && editor?.setValue(props.value);
        }
    }, [props.value]);

    return (
        <Container ref={monacoEl}></Container>
    );
};

export default SimpleEditor;


const Container = styled.div`
    width: 100%;
    height: 100%;
`;